package com.thh.redisstudy.service;

import com.thh.redisstudy.entity.SysUser;
import com.thh.redisstudy.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author kaizen
 * @since 2019-07-20
 **/
@Service
@CacheConfig(cacheNames="userInfoCache") // 本类内方法指定使用缓存时，默认的名称就是userInfoCache
@Transactional(propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
public class UserService {

    @Autowired
    private SysUserMapper userMapper;

    @CachePut(key="#p0.id")  //#p0表示第一个参数
    public SysUser insertUser(SysUser u){
        userMapper.insert(u);
        return u;
    }

    @CachePut(key="#p0.id")
    public SysUser updateUser(SysUser u){
        this.userMapper.updateByPrimaryKey(u);
        //可能只是更新某几个字段而已，所以查次数据库把数据全部拿出来全部
        return this.userMapper.selectByPrimaryKey(u.getId());
    }

    @Nullable
    @Cacheable(key="#p0") // @Cacheable 会先查询缓存，如果缓存中存在，则不执行方法
    public SysUser findById(Integer id){
        return this.userMapper.selectByPrimaryKey(id);
    }

    @CacheEvict(key="#p0")  //删除缓存名称为userInfoCache,key等于指定的id对应的缓存
    public void deleteById(Integer id){
        this.userMapper.deleteByPrimaryKey(id);
    }

    @Nullable
    @Cacheable(value = "UserInfoList", keyGenerator = "simpleKeyGenerator") // @Cacheable 会先查询缓存，如果缓存中存在，则不执行方法
    public SysUser findByIdTtl(Integer id){
        System.err.println("根据id=" + id +"获取用户对象，从数据库中获取");
        Assert.notNull(id,"id不用为空");
        return this.userMapper.selectByPrimaryKey(id);
    }


}
